import 'package:shared_preferences/shared_preferences.dart';

/// SharedPreferences 工具类
/// 提供数据持久化存储功能的静态方法集合
class Preferences {
  static SharedPreferences? _prefs;

  /// 私有构造函数，防止实例化
  Preferences._();

  /// 初始化 SharedPreferences 实例
  /// 应用启动时调用一次
  static Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  /// 确保 SharedPreferences 实例已初始化
  static Future<SharedPreferences> _getInstance() async {
    _prefs ??= await SharedPreferences.getInstance();
    return _prefs!;
  }

  /// 保存字符串数据
  static Future<bool> setString(String key, String value) async {
    final prefs = await _getInstance();
    return prefs.setString(key, value);
  }

  /// 获取字符串数据
  static Future<String?> getString(String key, [String? defaultValue]) async {
    final prefs = await _getInstance();
    return prefs.getString(key) ?? defaultValue;
  }

  /// 保存整型数据
  static Future<bool> setInt(String key, int value) async {
    final prefs = await _getInstance();
    return prefs.setInt(key, value);
  }

  /// 获取整型数据
  static Future<int?> getInt(String key, [int? defaultValue]) async {
    final prefs = await _getInstance();
    return prefs.getInt(key) ?? defaultValue;
  }

  /// 保存布尔型数据
  static Future<bool> setBool(String key, bool value) async {
    final prefs = await _getInstance();
    return prefs.setBool(key, value);
  }

  /// 获取布尔型数据
  static Future<bool?> getBool(String key, [bool? defaultValue]) async {
    final prefs = await _getInstance();
    return prefs.getBool(key) ?? defaultValue;
  }

  /// 保存浮点型数据
  static Future<bool> setDouble(String key, double value) async {
    final prefs = await _getInstance();
    return prefs.setDouble(key, value);
  }

  /// 获取浮点型数据
  static Future<double?> getDouble(String key, [double? defaultValue]) async {
    final prefs = await _getInstance();
    return prefs.getDouble(key) ?? defaultValue;
  }

  /// 保存字符串列表数据
  static Future<bool> setStringList(String key, List<String> value) async {
    final prefs = await _getInstance();
    return prefs.setStringList(key, value);
  }

  /// 获取字符串列表数据
  static Future<List<String>?> getStringList(
    String key, [
    List<String>? defaultValue,
  ]) async {
    final prefs = await _getInstance();
    return prefs.getStringList(key) ?? defaultValue;
  }

  /// 删除指定键的数据
  static Future<bool> remove(String key) async {
    final prefs = await _getInstance();
    return prefs.remove(key);
  }

  /// 清空所有数据
  static Future<bool> clear() async {
    final prefs = await _getInstance();
    return prefs.clear();
  }

  /// 重新加载数据（从磁盘重新加载）
  static Future<void> reload() async {
    final prefs = await _getInstance();
    await prefs.reload();
  }
}
